package com.xyf.sys.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xyf.sys.config.MiniprogramConfig;
import com.xyf.sys.domain.*;
import com.xyf.sys.mapper.SysCartItemMapper;
import com.xyf.sys.service.*;
import com.xyf.sys.vo.CartPreOrder;
import com.xyf.sys.vo.OrderVo;
import com.xyf.sys.vo.PreOrderResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author R-H
 * @Date 2024/4/201158
 * @Description
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class CartItemServiceImpl implements ICartItemService {

    @Autowired
    private SysCartItemMapper mapper;
    @Lazy
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IProductService productService;
    @Autowired
    private IProductOptionService productOptionService;
    @Autowired
    private IUserService userService;
    @Autowired
    @Qualifier(value = "clientConfig")
    private MiniprogramConfig.MiniConfig clientConfig;
    @Autowired
    @Qualifier(value = "manageConfig")
    private MiniprogramConfig.MiniConfig manageConfig;
    @Autowired
    private IWechatService wechatService;
    @Autowired
    private IGoodsService goodsService;


    @Override
    public SysCartItem get(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<SysCartItem> getProductCartList(Long cartId, Long productId) {
        return mapper.selectByCartIdAndProductId(cartId, productId);
    }

    @Override
    public SysCartItem insert(SysCartItem cartItem) {
        cartItem.setTimestamp(new Date());
        cartItem.setLastUpdateTime(new Date());
        cartItem.setCreateTime(new Date());
        cartItem.setStatus("0");
        cartItem.setDelFlag("0");
        mapper.insert(cartItem);
        return cartItem;
    }

    @Override
    public void update(SysCartItem cartItem) {
        cartItem.setLastUpdateTime(new Date());
        cartItem.setUpdateTime(new Date());
        mapper.updateByPrimaryKey(cartItem);
    }

    @Override
    public List<SysCartItem> getCartItemList(Long cartId) {
        return mapper.selectByCartIdAndDelFlag(cartId, "0");
    }

    @Override
    public int delete(Long id) {
        return mapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<SysCartItem> getCartItemList(String userId) {
        List<SysCartItem> items = mapper.selectByUserId(userId);
        if (!CollectionUtils.isEmpty(items)){
            for (SysCartItem item : items) {
                SysProduct product = productService.get(item.getProductId());
                if (product != null){
                    item.setName(product.getName());
                    item.setCategoryId(product.getCategoryId());
                    item.setTypeId(product.getTypeId());
                    item.setSketch(product.getSketch());
                    item.setIntro(product.getIntro());
                    item.setKeywords(product.getKeywords());
                    item.setTags(product.getTags());
                    item.setPrice(product.getPrice());
                    item.setUnit(product.getUnit());
                    item.setTags(product.getTags());
                    item.setMarketPrice(product.getMarketPrice());
                    item.setPictureUrl(product.getPictureUrl());
                    List<Long> colorIds = JSONArray.parseArray(item.getColorId(), Long.class);
                    item.setColorIds(colorIds);
                    item.setColorOptions(productOptionService.getList(colorIds));
                    List<Long> serveIds = JSONArray.parseArray(item.getServeId(), Long.class);
                    item.setServeIds(serveIds);
                    item.setServeOptions(productOptionService.getList(serveIds));
                    List<Long> defectIds = JSONArray.parseArray(item.getDefectId(), Long.class);
                    item.setDefectIds(defectIds);
                    item.setDefectOptions(productOptionService.getList(defectIds));
                    List<Long> affixIds = JSONArray.parseArray(item.getAffixId(), Long.class);
                    item.setAffixIds(affixIds);
                    item.setAffixOptions(productOptionService.getList(affixIds));
                } else {
                    Goods goods = goodsService.get(item.getProductId());
                    item.setName(goods.getName());
                    item.setSketch(goods.getSketch());
                    item.setIntro(goods.getIntro());
                    item.setKeywords(goods.getKeywords());
                    item.setTags(goods.getTags());
                    item.setPrice(goods.getPrice());
                    item.setTags(goods.getTags());
                    item.setMarketPrice(goods.getMarketPrice());
                    item.setPictureUrl(goods.getAttachUrl());
                }
            }
        }
        return items;
    }

    @Override
    public void clear(String userId) {
        List<SysCartItem> cartItemList = this.getCartItemList(userId);
        for (SysCartItem sysCartItem : cartItemList) {
            mapper.deleteByPrimaryKey(sysCartItem.getId());
        }
    }

    @Override
    public PreOrderResponseVo createPreOrder(CartPreOrder cartPreOrder) {
        if (cartPreOrder.isClient()){
            Order order = orderService.createCartOrder(cartPreOrder.getUserId(), cartPreOrder.getRecMan(), cartPreOrder.getAppid(), cartPreOrder.getUserMobile(), cartPreOrder.getPickUpDate(), cartPreOrder.getPickUpRange(), cartPreOrder.getOrderImg(), cartPreOrder.getRemark(), cartPreOrder.getDeptId());
            // 查询团长
            List<User> userList = userService.getUserList(manageConfig.getAppid(), order.getDeptId());
            if (!CollectionUtils.isEmpty(userList)) {
                OrderVo detail = orderService.getDetail(order.getId());
                for (User user : userList) {
                    if (StringUtils.isNotBlank(user.getUnionid())) {
                        User accountUser = userService.getUser(user.getUnionid(), "wxa33105ce83dddd01");
                        if (accountUser != null){
                            try {
                                JSONObject object = wechatService.sendLaundryTemplateMessage("wxa33105ce83dddd01", "5506a050467515ccdb28c44f6a25f652", "UJYMG27-VxWdDjl4K-5ExyDzhrE-oSC1d-hI8hULv6A", accountUser.getOpenid(), detail);
                                if (object != null && object.getInteger("errcode") == 0) {
                                    log.info("template message send to touser {} success ", user.getOpenid());
                                } else {
                                    log.error("template message send err {}", object.toString());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                log.error("send template message err {}", e);
                            }
                        } else {
                            log.warn("order id not found public account user {} openid {} ", order.getId(), order.getRegimentId());
                        }
                    }
                }
            }
            if (cartPreOrder.getNowPay() != null && cartPreOrder.getNowPay()){
                return orderService.pay(order.getId(), order.getUserId(), cartPreOrder.getAppid());
            }
            PreOrderResponseVo responseVo = new PreOrderResponseVo();
            responseVo.setOrder(order);
            responseVo.setOrderId(order.getId());
            return responseVo;
        } else {
            List<Long> ids = cartPreOrder.getIds();
            List<SysCartItem> list = new ArrayList<>(ids.size());
            for (Long id : ids) {
                SysCartItem sysCartItem = this.get(id);
                list.add(sysCartItem);
            }
            Order order = null;
            if (StringUtils.isBlank(cartPreOrder.getOrderId())){
                order = orderService.createCartOrder(list, cartPreOrder.getUserId(), cartPreOrder.getUserId(), cartPreOrder.getAppid(), cartPreOrder.getUserMobile(), cartPreOrder.getUserName(), cartPreOrder.getDeptId());
            } else {
                order = orderService.updateCartOrder(cartPreOrder.getOrderId(), list, cartPreOrder.getUserId());
            }
            list.stream().forEach(cartItem -> {
                cartItem.setStatus("1");
                cartItem.setUpdateBy(cartPreOrder.getUserId());
                this.update(cartItem);
            });
            if (cartPreOrder.getNowPay() != null && cartPreOrder.getNowPay()){
                return orderService.pay(order.getId(), cartPreOrder.getUserId(), cartPreOrder.getAppid());
            }
            PreOrderResponseVo responseVo = new PreOrderResponseVo();
            responseVo.setOrder(order);
            responseVo.setOrderId(order.getId());
            return responseVo;
        }
    }
}
